import api from 'index'
import { AppId } from 'config'
import { userInfoStore } from '../store/userInfo'
var WXBizDataCrypt = require('../utils/RdWXBizDataCrypt.js');
const app = getApp();

export default {

  savePhoneNumber(data = {}, callback){
    let { session_key } = userInfoStore.userInfo;
    let pc = new WXBizDataCrypt(AppId, session_key);
    var ret = pc.decryptData(data.encryptedData, data.iv)
    console.log('解密后 data: ', ret)

    var param = {
      openId: userInfoStore.userInfo.openId,
      phone: ret.phoneNumber,
      level: 1
    }
    if (app.globalData.inviteCode)
      param = Object.assign(param, { recomendCode: app.globalData.inviteCode })
    
    api.saveUser(param).then(res => {
      let { userInfo } = userInfoStore;
      let { result } = res;
      result.session_key = userInfo.session_key;
      userInfoStore.updateUserInfo(result);
      if (callback) callback();
    }, err => {
      wx.showModal({
        title: "提交失败",
        content: err,
        showCancel: false,
        confirmText: "我知道了"
      })
    })
  }  

}